package com.stedu.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.bean.Book;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.service.AdminService;
import com.stedu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/book")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private AdminService adminService;

    @Value("${pageSize}")
    private Integer pageSize;

    //分页
    @GetMapping
    public RespBean selectByPage(Integer pageNum, String bname, String bauthor){
        if (pageNum == null){
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);

        List<Book> bnameAll = bookService.selectByBname(bname, bauthor);

        PageInfo<Book> pageInfo = new PageInfo<>(bnameAll, 5);

        return RespBean.ok("查询成功", pageInfo);
    }

    //添加
    @PostMapping
    public RespBean insertController(@RequestBody  Book book) {
        if (bookService.insertBook(book)){
            return RespBean.ok("添加成功");
        }else{
            return RespBean.error("添加失败");
        }
    }

    //删除
    @DeleteMapping("{bid}")
    public RespBean deleteController(@PathVariable Integer bid){
        if (bookService.deleteBook(bid)){
            return RespBean.ok("删除成功");
        }else{
            return RespBean.error("删除失败");
        }
    }

    //修改
    @PutMapping
    public RespBean updateController(@RequestBody Book book){
        if (bookService.updateBook(book)){
            return RespBean.ok("修改成功");
        }else{
            return RespBean.error("修改失败");
        }
    }

    //根据书名查询
    @GetMapping("/ByBname")
    public RespBean selectByBnameController(@RequestBody String bname, String bauthor){
        if (bookService.selectByBname(bname, bauthor) != null){
            List<Book> unameAll = bookService.selectByBname(bname, bauthor);
            return RespBean.ok("查询成功", unameAll);
        }else{
            return  RespBean.error("查询不到,请确定姓名");
        }
    }

    //根据书ID查询
    @GetMapping("/ByBid/{bid}")
    public RespBean selectByBidController(@PathVariable Integer bid){
        if (bookService.selectByBid(bid) != null){
            Book book = bookService.selectByBid(bid);
            return RespBean.ok("查询成功", book);
        }else {
            return RespBean.error("查询失败,没有该用户");
        }
    }

    //搜索框中根据ID查询
    @GetMapping("/BC")
    public RespBean selectByBAndC(@RequestBody String bname){
        if (bookService.BookWithClassifies(bname) != null){
            Book book = bookService.BookWithClassifies(bname);
            return RespBean.ok("查询成功", book);
        }else{
            return RespBean.error("查询失败，没有该用户ID");
        }
    }

    //查询所有
    @GetMapping("/All")
    public RespBean selectAllController(){
        List<Book> books = bookService.selectAll();
        return RespBean.ok("查询成功", books);
    }

    //分类并查询
    @GetMapping("/BidAndCid/{cname}")
    public RespBean selectBidAndCidController(@PathVariable String cname) {
        List<Map<String, Object>> categoryInfos = bookService.selectBidAndCid(cname);
        return RespBean.ok("查询成功", categoryInfos);
    }

    @GetMapping("/selectByCid/{cid}")
    public RespBean selectByCid(@PathVariable Integer cid) {
        List<Book> books = bookService.selectBycid(cid);
        return RespBean.ok("查询成功", books);
    }

    //查询所有书籍
    @GetMapping("/Book")
    public RespBean selectBook(){
        List<Book> books = bookService.selectBook();
        return RespBean.ok("", books);
    }

    //获取用户信息
    @GetMapping("/Admin/{bid}")
    public RespBean allAdmin(@PathVariable ("bid") Integer bid){
        List<Map<String, Object>> adminMapList = adminService.selectByAname(null)
                .stream()
                .filter(a -> a.getPermissions() == 1)
                .map(a -> {
                    Map<String, Object> adminMap = new HashMap<>();
                    adminMap.put("key", a.getAid());
                    adminMap.put("label", a.getAid() + " " + "-" + " " + a.getAname());
                    return adminMap;
                }).collect(Collectors.toList());

        //获取已经分配的用户aid
        List<Integer> aids = bookService.selectAidByBid(bid);

        Map<String, Object> map = new HashMap<>();

        map.put("allAdmin", adminMapList);
        map.put("selectdAids", aids);

        return  RespBean.ok("", map);
    }

    @PostMapping("/bidAndAid")
    public RespBean insertBidAndAid(@RequestBody Map<String, Object> map){
        System.out.println(map);

        Integer bid = (Integer) map.get("bid");
        List<Integer> aidsList = (List<Integer>) map.get("aids");
        Integer[] aids = new Integer[aidsList.size()];
        for (int i = 0; i < aidsList.size(); i++){
            int aid = aidsList.get(i);
            aids[i] = new Integer(aid + "");
        }
        bookService.insertBidAndAid(bid, aids);
        return RespBean.ok("分配用户成功");
    }

    @GetMapping("/exp")
    public void exp(HttpServletResponse response) throws SteduException, IOException {
        List<Book> books = bookService.selectAll();

        if(CollectionUtil.isEmpty(books)){
            throw new SteduException("未找到数据");
        }

        List<Map<String, Object>> list = new ArrayList<>(books.size());

        for (Book book : books){
            Map<String, Object> map = new HashMap<>();
            map.put("书籍ID", book.getBid());
            map.put("书籍图像", book.getBAvatar());
            map.put("书名", book.getBname());
            map.put("作者", book.getBauthor());
            map.put("出版社", book.getBpress());
            map.put("出版日期", book.getBdate());
            map.put("书籍数量", book.getBnumber());
            map.put("分类ID", book.getClassify().getCid());
            map.put("分类名称", book.getClassify().getCname());

            list.add(map);
        }

        // 使用 Hutool 的 ExcelWriter 来生成 Excel 文件
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("content-Disposition", "attachment;filename=type.xlsx");

        // 获取输出流并将 Excel 文件写入输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        out.close();
    }

    @PostMapping("/pxe")
    public void pxe(MultipartFile file) throws IOException {
        List<Book> infolist = ExcelUtil.getReader(file.getInputStream()).readAll(Book.class);
        if(!CollectionUtil.isEmpty(infolist)){
            for(Book book : infolist){
                try {
                    bookService.insertBook(book);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }


}
